package com.woniuxy.service.impl;

import com.woniuxy.entity.Mail;
import com.woniuxy.service.DelayService;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: 马宇航
 * @Description: 延迟消息 重点
 * @DateTime: 22/10/20/0020 16:30
 * @Component: 成都蜗牛学苑
 **/
@Service
public class DelayServiceImpl implements DelayService {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public void sendDelayMessage(Mail mail) {
        rabbitTemplate.convertAndSend("delayExchange", "delay", mail,
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        //当作延迟具体的时间
                        double weight = mail.getWeight();
                        Integer tims = new Integer((int) weight);
                        //持久化配置
                        message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                        //这里设置一个消息头，配置 x-delay
                        message.getMessageProperties().setDelay(tims);
                        return message;
                    }
                });
    }
}
